<template>
  <!-- 动态需量管理 -->
  <div class="filterContent">
    <a-form :model="filterForm" layout="inline">
      <a-form-item label="">
        <a-radio-group
          v-model:value="filterForm.chartType"
          @change="changeChartType"
        >
          <a-radio-button value="total" v-if="isShowPoint"
            >总需量</a-radio-button
          >
          <a-radio-button value="single">各变压器需量</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="电站">
        <a-select
          ref="select"
          v-model:value="filterForm.stationId"
          class="formSelect"
          placeholder="选择电站"
          show-search
          optionFilterProp="label"
          @change="changeStation"
        >
          <a-select-option
            v-for="item in stationtList"
            :value="item.stationId"
            :key="item.stationId"
            :label="item.stationName"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-button
        type="primary"
        class="yellowBtn"
        @click="handleConfig"
        :disabled="!filterForm.stationId"
        v-hasPermission="'dynamicDemandConfig'"
        >动态需量配置</a-button
      >
    </a-form>
  </div>
  <div class="chartContent">
    <div class="title">
      <a-form :model="filterForm" layout="inline">
        <a-form-item label="选择月份">
          <a-date-picker
            v-model:value="filterForm.date"
            value-format="YYYY-MM"
            format="YYYY-MM"
            picker="month"
            :allowClear="false"
            separator="~"
          />
        </a-form-item>
        <a-form-item label="电池堆" v-if="filterForm.chartType === 'single'">
          <a-select
            v-model:value="filterForm.linkDeviceId"
            class="formInput"
            placeholder="请选择"
            :disabled="!filterForm.stationId"
            style="width: 150px"
          >
            <a-select-option
              v-for="item in energyLinkList"
              :value="item.deviceId"
              :key="item.deviceId"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-button type="primary" class="filterBtn" @click="getDemandData"
          >查询</a-button
        >
      </a-form>
      <a-spin
        :spinning="chartLoading"
      >
        <div class="demand">
          {{ filterForm.chartType === "total" ? "总需量" : "需量" }}：{{
            demandNum || "--"
          }}
        </div>
        <div
          id="dynaminDemand"
          class="chartContainer"
        />
      </a-spin>
    </div>
  </div>

  <DemandConfig
    :demandConfigVisible="demandConfigVisible"
    :stationId="filterForm.stationId"
    @update:demandConfigVisible="(val) => (demandConfigVisible = val)"
  />
</template>
<script setup>


import * as echarts from "echarts";
import { cloneDeep } from "lodash-es";
import { chartOption } from "./chartOption";
import DemandConfig from "./components/demandConfig.vue";
const $api = inject("$api");
const filterForm = ref({
  stationId: null,
  date: null,
  chartType: "single",
});
const chartLoading = ref(false);
const chartsData = ref([]);
const demandConfigVisible = ref(false);
const demandChart = ref({});
const handleConfig = () => {
  demandConfigVisible.value = true;
};
// 查看是否存在计量点
const isShowPoint = ref(false);
const checkPoint = async () => {
  const params = {
    stationId: filterForm.value.stationId,
  };
  const res = await $api.containPoint(params);
  if (res?.data) {
    isShowPoint.value = true;
  } else {
    isShowPoint.value = false;
  }
};
const stationtList = ref([]);
const getCompanyStationtList = async () => {
  const res = await $api.companyStationtList({
    billingMethod: 2, // 只显示 需量计费 的用户
  });
  if (res?.code === 0) {
    stationtList.value = res.data;
    filterForm.value.stationId = res?.data?.[0]?.stationId;
    if (filterForm.value.stationId) {
      changeStation(filterForm.value.stationId);
    }
  }
};
const changeStation = (val) => {
  filterForm.value.chartType = "single";
  filterForm.value.linkDeviceId = null;
  checkPoint();
  getEnergyLinkList(val);
};
const getDemandData = async () => {
  const params = {
    stationId: filterForm.value.stationId,
    month: filterForm.value.date,
  };
  chartLoading.value = true;

  if (filterForm.value.chartType === "single") {
    params.linkDeviceId = filterForm.value.linkDeviceId; // 如果是选择各变压器需量，则需要传电池堆id
    await getDemand();
  } else if (filterForm.value.chartType === "total") {
    await getTotLDemand();
  }
  const res = await $api.dynamicDemand(params);
  chartLoading.value = false;
  if (!res?.data.length) {
    chartsData.value = [];
    return;
  }
  chartsData.value = res.data;
  demandChart.value = cloneDeep(chartOption);
  // const res = resList.filter((item) => item);
  demandChart.value.series[0].data = res.data.map((item) => item.value);
  switch (filterForm.value.chartType) {
    case "total":
      demandChart.value.title.text = "总需量监控";
      break;
    case "single":
      demandChart.value.title.text = "需量监控";
      break;
    default:
      break;
  }
  demandChart.value.series[0].markLine.data[0].yAxis = demandNum.value;
  if (demandNum.value) {
    demandChart.value.yAxis.max = Math.max(
      demandNum.value,
      ...demandChart.value.series[0].data
        .map((item) => Number(item))
        .filter((d) => d)
    );
  }

  demandChart.value.xAxis.data = res.data.map(
    (item) => item.dateTime.split(" ")[0]
  );
  await nextTick();
  const chartEl = document.getElementById("dynaminDemand");
  if (chartEl) {
    const chartInstance = echarts.init(chartEl);
    chartInstance.resize();
    chartInstance.clear();
    chartInstance.setOption(demandChart.value);
  }
};
// 电池堆list
const energyLinkList = ref([]);
const getEnergyLinkList = async (id) => {
  const params = { 
    stationId: id,
    isMain: 1, // 动态需量这里需要加上isMain字段
  };
  const res = await $api.energyLinkList(params);
  if (res && res.code === 0) {
    energyLinkList.value = res.data;
    filterForm.value.linkDeviceId = energyLinkList.value?.[0]?.deviceId;
    getDemandData();
  }
};
// 需量查询
const linkDemandList = ref([]);
const getDemand = async () => {
  const res = await $api.checkLinkDemand({
    stationId: filterForm.value.stationId,
  });
  if (res?.data) {
    linkDemandList.value = res.data;
  } else {
    linkDemandList.value = [];
  }
};
// 总需量查询
const totalDemandList = ref([]);
const getTotLDemand = async () => {
  const res = await $api.checkTotalDemand({
    stationId: filterForm.value.stationId,
  });
  if (res?.data) {
    totalDemandList.value = res.data;
  } else {
    totalDemandList.value = [];
  }
};
const demandNum = computed(() => {
  if (filterForm.value.chartType === "total") {
    return totalDemandList.value?.[0]?.demand;
  } else if (filterForm.value.chartType === "single") {
    return linkDemandList.value?.[0]?.demand;
  }
});
onMounted(async () => {
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, "0");
  filterForm.value.date = `${year}-${month}`; // 默认赋值当前月份
  getCompanyStationtList();
});
</script>

<style lang="less" scoped>
.chartContent {
  border: 1px solid #666;
  border-radius: 4px;
  padding: 20px;
  background-color: #141414;
}
.filterBtn {
  display: inline-block;
}
.formSelect {
  width: 200px;
}
.chartContainer {
  width: 100%;
  height: 500px;
}
.demand {
  margin-top: 20px;
  font-size: 16px;
}
</style>